# coding: utf-8
import json

import requests
import sqlite3

import Utils

if __name__ == "__main__":
    conn = sqlite3.connect(Utils.SQLITE_DB)
    cursor = conn.cursor()
    cursor.execute(Utils.SQLITE_DROP_TABLE)
    cursor.execute(Utils.SQLITE_CREATE_TABLE)
    count = 0
    max_page = 1
    while (count < max_page):
        r = requests.post(Utils.build_post_url(count), data='{}', headers=Utils.HEADERS)
        if (max_page == 1):
            max_page = json.loads(r.text)['totalPages']
        for data in r.json()['content']:
            item = json.loads(json.dumps(data), object_hook=Utils.handle)
            cursor.execute(Utils.build_sqlite_insert_sql(item.values_2_string()))
            conn.commit()
            print("item " + str(count) + ":" + item.values_2_string())
        count = count + 1
    conn.close()
